using Intelli.Cust.Service.mvc.Models;
using Intelli.Cust.Service.mvc.Services;
using Microsoft.AspNetCore.Mvc;

namespace Intelli.Cust.Service.mvc.Controllers
{
    public class ChatController : Controller
    {
        private readonly IIntelligentCustomerServiceClient _chatService;
        private readonly ILogger<ChatController> _logger;

        public ChatController(IIntelligentCustomerServiceClient chatService, ILogger<ChatController> logger)
        {
            _chatService = chatService;
            _logger = logger;
        }

        public IActionResult Index()
        {
            // 生成新的会话ID
            var sessionId = Guid.NewGuid().ToString();
            var userId = $"user_{DateTime.Now:yyyyMMddHHmmss}";
            
            ViewBag.SessionId = sessionId;
            ViewBag.UserId = userId;
            
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> SendMessage([FromBody] ChatRequest request)
        {
            try
            {
                var response = await _chatService.SendMessageAsync(request);
                return Json(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息时发生错误");
                return Json(new ChatResponse
                {
                    Content = "抱歉，发生错误，请稍后重试。",
                    ErrorMessage = ex.Message
                });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetHistory(string sessionId, int limit = 10)
        {
            try
            {
                var history = await _chatService.GetConversationHistoryAsync(sessionId, limit);
                return Json(history);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取对话历史时发生错误");
                return Json(new List<ChatMessage>());
            }
        }

        [HttpPost]
        public async Task<IActionResult> RateResponse([FromBody] RateRequest request)
        {
            try
            {
                var success = await _chatService.RateResponseAsync(
                    request.SessionId, 
                    request.MessageId, 
                    request.Rating, 
                    request.Feedback);
                
                return Json(new { success, message = success ? "评价提交成功" : "评价提交失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "评价回复时发生错误");
                return Json(new { success = false, message = "评价提交失败" });
            }
        }

        public IActionResult Knowledge()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> InitializeKnowledgeBase()
        {
            try
            {
                var success = await _chatService.InitializeKnowledgeBaseAsync();
                return Json(new { success, message = success ? "知识库初始化成功" : "知识库初始化失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化知识库时发生错误");
                return Json(new { success = false, message = "知识库初始化失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> AddKnowledgeDocument([FromBody] KnowledgeDocumentRequest request)
        {
            try
            {
                var success = await _chatService.AddKnowledgeDocumentAsync(request.Document, request.Metadata);
                return Json(new { success, message = success ? "文档添加成功" : "文档添加失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加知识库文档时发生错误");
                return Json(new { success = false, message = "文档添加失败" });
            }
        }
    }

    public class RateRequest
    {
        public string SessionId { get; set; } = string.Empty;
        public string MessageId { get; set; } = string.Empty;
        public int Rating { get; set; }
        public string? Feedback { get; set; }
    }

    public class KnowledgeDocumentRequest
    {
        public string Document { get; set; } = string.Empty;
        public Dictionary<string, object> Metadata { get; set; } = new();
    }
} 